package com.olap.starter.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.olap.starter.common.service.cache.TableMainCaCheService;
import com.olap.starter.core.base.BaseService;
import com.olap.starter.mapper.TableMainMapper;
import com.olap.starter.util.IdUtil;
import com.olap.starter.pojo.TableMain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 * 服务类
 * </p>
 *
 * @author WBG
 * @since 2022-08-31
 */
@Service
public class TableMainServices extends BaseService<TableMainMapper, TableMain> {

    @Autowired
    private TableMainCaCheService tableMainCaCheService;

    @Override
    public boolean save(TableMain entity) {
        if (entity.getUuid() == null) {
            entity.setUuid(new IdUtil().nextId());
        }
        if(entity.getVersion() == null){
            entity.setVersion(1);
        }
        entity.setUpdateInfo("初始化配置");
        entity.setDeleted(0);
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateTime(LocalDateTime.now());
        //entity.setId(IdWorker.getId());
        boolean save = super.save(entity);
        tableMainCaCheService.reloadCache(entity.getUuid());
        return save;
    }

    @Override
    @Transactional
    public boolean updateById(TableMain entity) {
        return updateByUuid(entity);
    }

    @Transactional
    public boolean updateByUuid(TableMain entity) {
        update(new LambdaUpdateWrapper<TableMain>().eq(TableMain::getUuid, entity.getUuid()).set(TableMain::getDeleted, 1));
        entity.setId(null);
        Integer maxVersionByUuid = this.baseMapper.getMaxVersionByUuid(entity.getUuid());
        if (maxVersionByUuid == null) {
            maxVersionByUuid = 0;
        }
        entity.setVersion(maxVersionByUuid + 1);
        entity.setDeleted(0);
        boolean save = save(entity);
        tableMainCaCheService.reloadCache(entity.getUuid());
        return save;
    }
}
